<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>设备方向速度案例之摇动手机播放音乐</title>
</head>

<body>
    <div id="device-info">设备方向、速度</div>
    <audio src="./asd.mp3"></audio>
    <script src="https://cdn.bootcdn.net/ajax/libs/vConsole/3.9.0/vconsole.min.js"></script>
    <script src="https://cdn.bootcdn.net/ajax/libs/lodash.js/4.17.21/lodash.js"></script>
    <script>
        var vConsole = new VConsole();
    </script>
    <script>
        (function () {
            let oDeviceInfoDom = document.getElementById('device-info'),
                accDiff = 30,
                lastTime = new Date().getTime(),
                oAudio = document.getElementsByTagName('audio')[0],
                ts = [];

            function init() {
                bindEvent();
            }

            function bindEvent() {
                window.addEventListener('devicemotion', _.throttle(function (e) {
                    let { x, y, z } = e.acceleration,
                        currentTime = new Date().getTime();
                    if (currentTime - lastTime > 1000) {
                        if (Math.abs(x) > accDiff || Math.abs(y) > accDiff || Math.abs(z) > accDiff) {
                            if (oAudio) {
                                if (ts.length > 0) {
                                    ts.forEach(t => {
                                        clearTimeout(t);
                                    })
                                    ts = [];
                                }
                                oAudio.play();
                                var t = setTimeout(function () {
                                    oAudio.pause();
                                }, 5000);
                                ts.push(t);
                            }
                        }
                    }
                }))
            }

            init();
        })()
    </script>
</body>

</html>